package com.visionblue.business.ship.page.dialog

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.visionblue.business.ship.R
import com.visionblue.business.ship.model.repository.db.CachedOrder
import com.visionblue.business.ship.model.repository.db.RecordAndOrderRelation
import com.visionblue.business.ship.page.collection.CollectionActivity
import com.visionblue.business.ship.util.FormatUtils
import com.visionblue.business.ship.util.StringUtils
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_cached_order.*

/**
 * @author: xlh
 * @date: 2020-06-05 3:30 PM
 * @desc:
 */
class CachedOrderAdapter : RecyclerView.Adapter<CachedOrderAdapter.VH>() {

    private val orders = mutableListOf<RecordAndOrderRelation>()

    var onItemClickListener: OnItemClickListener? = null

    class VH(override val containerView: View) : RecyclerView.ViewHolder(containerView),
        LayoutContainer

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.item_cached_order, parent, false)
        return VH(itemView)
    }

    override fun getItemCount() = orders.size

    override fun onBindViewHolder(holder: VH, position: Int) {
        val cachedOrder = orders[position].cachedOrder
        holder.tvShipName.text = cachedOrder.companyName ?: "未指定对象"
        val endTime = cachedOrder.endTime
        endTime?.let {
            holder.tvDate.text = StringUtils.getString(
                R.string.saved_date_format,
                FormatUtils.formatTimeYMDHHmm(it)
            )
        }

        holder.itemView.setOnClickListener {
            CollectionActivity.start(it.context,"暂存单", id = cachedOrder.id)
            onItemClickListener?.onItemClick(position)
        }
    }

    fun setData(orders: List<RecordAndOrderRelation>?) {
        if (orders != null) {
            this.orders.clear()
            this.orders.addAll(orders)
            notifyDataSetChanged()
        }
    }

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

}